from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
import json

from .models import Template, ProcessingTask, UploadedFile, SystemLog


@admin.register(Template)
class TemplateAdmin(admin.ModelAdmin):
    """模板管理"""
    
    list_display = [
        'name', 'description', 'is_active', 'template_file_link', 
        'created_at', 'updated_at', 'action_buttons'
    ]
    list_filter = ['is_active', 'created_at', 'updated_at']
    search_fields = ['name', 'description']
    readonly_fields = ['created_at', 'updated_at', 'config_preview']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'is_active', 'template_file')
        }),
        ('配置信息', {
            'fields': ('mapping_config', 'fixed_config', 'pol_config', 'shipper_config'),
            'classes': ('collapse',)
        }),
        ('预览', {
            'fields': ('config_preview',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def template_file_link(self, obj):
        """模板文件链接"""
        if obj.template_file:
            return format_html(
                '<a href="{}" target="_blank">{}</a>',
                obj.template_file.url,
                obj.template_file.name.split('/')[-1]
            )
        return '-'
    template_file_link.short_description = '模板文件'
    
    def action_buttons(self, obj):
        """操作按钮"""
        buttons = []
        
        # 查看详情
        detail_url = reverse('core:template_detail', args=[obj.pk])
        buttons.append(f'<a href="{detail_url}" class="button">查看</a>')
        
        # 编辑
        edit_url = reverse('core:template_edit', args=[obj.pk])
        buttons.append(f'<a href="{edit_url}" class="button">编辑</a>')
        
        # 切换状态
        toggle_url = reverse('core:template_toggle', args=[obj.pk])
        toggle_text = '禁用' if obj.is_active else '启用'
        buttons.append(f'<a href="{toggle_url}" class="button">{toggle_text}</a>')
        
        return format_html(' | '.join(buttons))
    action_buttons.short_description = '操作'
    
    def config_preview(self, obj):
        """配置预览"""
        configs = {
            '映射配置': obj.mapping_config,
            '固定值配置': obj.fixed_config,
            '港口配置': obj.pol_config,
            '发货人配置': obj.shipper_config,
        }
        
        html_parts = []
        for name, config in configs.items():
            if config:
                json_str = json.dumps(config, indent=2, ensure_ascii=False)
                html_parts.append(f'<h4>{name}</h4><pre>{json_str}</pre>')
        
        return mark_safe('<br>'.join(html_parts)) if html_parts else '无配置'
    config_preview.short_description = '配置预览'


@admin.register(ProcessingTask)
class ProcessingTaskAdmin(admin.ModelAdmin):
    """处理任务管理"""
    
    list_display = [
        'task_name', 'template', 'status', 'progress', 
        'created_at', 'started_at', 'completed_at', 'action_buttons'
    ]
    list_filter = ['status', 'template', 'created_at']
    search_fields = ['task_name', 'template__name']
    readonly_fields = [
        'created_at', 'updated_at', 'started_at', 'completed_at',
        'result_files_preview', 'error_message_preview'
    ]
    
    fieldsets = (
        ('基本信息', {
            'fields': ('task_name', 'template', 'status', 'progress')
        }),
        ('文件信息', {
            'fields': ('result_files_preview',),
            'classes': ('collapse',)
        }),
        ('错误信息', {
            'fields': ('error_message_preview',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at', 'started_at', 'completed_at'),
            'classes': ('collapse',)
        }),
    )
    
    def result_files_preview(self, obj):
        """结果文件预览"""
        if obj.result_files:
            files = obj.result_files.get('files', [])
            if files:
                file_list = '<ul>' + ''.join([f'<li>{f}</li>' for f in files]) + '</ul>'
                return mark_safe(file_list)
        return '无结果文件'
    result_files_preview.short_description = '结果文件'
    
    def error_message_preview(self, obj):
        """错误信息预览"""
        if obj.error_message:
            return format_html('<pre style="color: red;">{}</pre>', obj.error_message)
        return '无错误'
    error_message_preview.short_description = '错误信息'
    
    def action_buttons(self, obj):
        """操作按钮"""
        buttons = []
        
        # 查看详情
        detail_url = reverse('core:task_detail', args=[obj.pk])
        buttons.append(f'<a href="{detail_url}" class="button">查看</a>')
        
        # 重新运行（仅失败或完成的任务）
        if obj.status in ['failed', 'completed']:
            restart_url = reverse('core:task_restart', args=[obj.pk])
            buttons.append(f'<a href="{restart_url}" class="button">重新运行</a>')
        
        return format_html(' | '.join(buttons))
    action_buttons.short_description = '操作'


@admin.register(UploadedFile)
class UploadedFileAdmin(admin.ModelAdmin):
    """上传文件管理"""
    
    list_display = [
        'original_name', 'file_type', 'template', 'file_size_display',
        'created_at', 'file_link', 'action_buttons'
    ]
    list_filter = ['file_type', 'template', 'created_at']
    search_fields = ['original_name', 'template__name']
    readonly_fields = ['created_at', 'file_size_display', 'file_info']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('original_name', 'file_type', 'template', 'file')
        }),
        ('文件信息', {
            'fields': ('file_size_display', 'file_info'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    
    def file_size_display(self, obj):
        """文件大小显示"""
        if obj.file:
            size = obj.file.size
            if size < 1024:
                return f'{size} B'
            elif size < 1024 * 1024:
                return f'{size / 1024:.1f} KB'
            else:
                return f'{size / (1024 * 1024):.1f} MB'
        return '-'
    file_size_display.short_description = '文件大小'
    
    def file_link(self, obj):
        """文件链接"""
        if obj.file:
            return format_html(
                '<a href="{}" target="_blank">下载</a>',
                obj.file.url
            )
        return '-'
    file_link.short_description = '文件'
    
    def file_info(self, obj):
        """文件信息"""
        if obj.file:
            info = [
                f'原始名称: {obj.original_name}',
                f'存储路径: {obj.file.name}',
                f'文件大小: {self.file_size_display(obj)}',
                f'上传时间: {obj.created_at.strftime("%Y-%m-%d %H:%M:%S")}',
            ]
            return format_html('<br>'.join(info))
        return '无文件信息'
    file_info.short_description = '文件详情'
    
    def action_buttons(self, obj):
        """操作按钮"""
        buttons = []
        
        # 下载文件
        if obj.file:
            download_url = reverse('core:file_download', args=[obj.pk])
            buttons.append(f'<a href="{download_url}" class="button">下载</a>')
        
        return format_html(' | '.join(buttons))
    action_buttons.short_description = '操作'


@admin.register(SystemLog)
class SystemLogAdmin(admin.ModelAdmin):
    """系统日志管理"""
    
    list_display = [
        'level', 'message_preview', 'module', 'function',
        'created_at', 'action_buttons'
    ]
    list_filter = ['level', 'module', 'created_at']
    search_fields = ['message', 'module', 'function']
    readonly_fields = ['created_at', 'message_full']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('level', 'module', 'function')
        }),
        ('日志内容', {
            'fields': ('message_full',)
        }),

        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    
    def message_preview(self, obj):
        """消息预览"""
        if len(obj.message) > 100:
            return obj.message[:100] + '...'
        return obj.message
    message_preview.short_description = '消息'
    
    def message_full(self, obj):
        """完整消息"""
        return format_html('<pre>{}</pre>', obj.message)
    message_full.short_description = '完整消息'
    
    def action_buttons(self, obj):
        """操作按钮"""
        # 可以添加查看相关任务等操作
        return '-'
    action_buttons.short_description = '操作'
    
    # 设置默认排序
    ordering = ['-created_at']
    
    # 设置每页显示数量
    list_per_page = 50


# 自定义管理后台标题
admin.site.site_header = 'CFS单证处理系统'
admin.site.site_title = 'CFS管理后台'
admin.site.index_title = '欢迎使用CFS单证处理系统管理后台'